package com.ifast.sys.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.ifast.common.base.CoreServiceImpl;
import com.ifast.common.domain.Tree;
import com.ifast.common.utils.BuildTree;
import com.ifast.sys.dao.DeptDao;
import com.ifast.sys.domain.DeptDO;
import com.ifast.sys.service.DeptService;
import com.xiaoleilu.hutool.util.StrUtil;

/**
 * <pre>
 * </pre>
 * <small> 2018年3月23日 | Aron</small>
 */
@Service
public class DeptServiceImpl extends CoreServiceImpl<DeptDao, DeptDO> implements DeptService {

    @Override
    public Tree<DeptDO> getTree(String depId) {
        List<Tree<DeptDO>> trees = Lists.newArrayList();
        List<DeptDO> sysDepts;
        if(StrUtil.isNotBlank(depId)){
            DeptDO tiJ = new DeptDO();
            tiJ.setId(depId);
            sysDepts = this.listDeptTree(tiJ);
        }else{
            sysDepts = this.list();
        }
        for (DeptDO sysDept : sysDepts) {
            Tree<DeptDO> tree = new Tree<DeptDO>();
            tree.setId(sysDept.getId());
            tree.setParentId(sysDept.getParentId());
            tree.setText(sysDept.getName());
            Map<String, Object> state = new HashMap<>(16);
            state.put("opened", false);
            tree.setState(state);
            trees.add(tree);
        }
        // 默认顶级菜单为０，根据数据库实际情况调整
        if(Objects.equal(depId,"1")){
            depId = "0";
        }else{
            DeptDO deptDO = this.getById(depId);
            depId = deptDO.getParentId();
        }
        return BuildTree.build(trees,depId);
    }

    @Override
    public boolean checkDeptHasUser(String deptId) {
        // 查询部门以及此部门的下级部门
        int result = baseMapper.getDeptUserNumber(deptId);
        return result == 0;
    }


    /**
     * 获取列表
     * @param page
     * @param deptDO
     * @return
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
    public IPage<DeptDO> listPage(Page page, DeptDO deptDO){
        return baseMapper.selectPage(page, new QueryWrapper<DeptDO>().like("name", deptDO.getName()).eq("ID", deptDO.getId()));
    }

    public List<DeptDO> listDeptTree(DeptDO deptDO){
        return baseMapper.listDeptTree(deptDO);
    }

    @Override
    public List<DeptDO> listDeptUpTree(DeptDO deptDO){
        return baseMapper.listDeptUpTree(deptDO);
    }



}
